import { taskType } from "../../enum";
import { initFormatStructureMemory } from "../../tools/memoryData";
import { getBodymoduleCount } from "../../tools/tools/creepTool";
import eventManager from "../event/eventManager";
import { eventMap } from "../event/eventMap"
import taskManager, { pushNeedResourceTask } from "../task/taskManager";

function _mountExtension() {
    Object.assign(StructureExtension.prototype, extension)
}

const extension = {
    init: function (params = {}) {
        const { taskPool = [] } = params
        this.taskPool = taskPool
        this.name = this.name || `${this.pos.roomName}能量电池${this.id}`
        // console.log(this.name + '完成采集，资源矿开始自检');
        this.checkSelf()
    },
    /**自检并执行任务*/
    run: function () {
        if (!this)return
        let objMemory = Memory.rooms[this.pos.roomName]['structure'][this.structureType][this.id]
        if (!objMemory.isRuning) {
            let isRuning = false
            // 非运行中，可执行任务
            if (objMemory.publishTask.length == 0) {
                this.updateSelfState()
                // 未发布任务，则进入自检，根据自检结果，判断是否发布任务
                if (objMemory.state.needEnergy) isRuning = pushNeedResourceTask(this, { [RESOURCE_ENERGY]: this.store.getFreeCapacity(RESOURCE_ENERGY) }, { taskID: `Extension编号${this.id}需求${RESOURCE_ENERGY}类型资源,数量为:${this.store.getFreeCapacity(RESOURCE_ENERGY)}` })
            }
            if (!isRuning) {
                // 无任务，则进入休眠状态，一段时间后自动唤醒
                objMemory.isRuning = true
                eventManager.add(`Extension点${this.id}进入休眠,等待唤醒`, 10, eventMap.objToSleep, { objID: this.id })
            }
        }
    },
    /**检查自身状态，避免出现异常数据 */
    checkSelf: function () {
        this.updateSelfState()
    },
    /**更新当前建筑的生命值 */
    checkSelfHits: function () {
        console.log(`当前建筑${this.name ? this.name : this.id}的生命值${this.hits ? this.hits : '*'}`);
    },
    /**更新自身状态
     * 1. 是否需要能量
     */
    updateSelfState: function () {
        let objMemory = this.room.memory['structure'][this.structureType][this.id]
        // 初始化
        if (!objMemory.state) initFormatStructureMemory(this)
        objMemory.state.needEnergy = false
        // 更新数据
        if (this.store.getFreeCapacity(RESOURCE_ENERGY)) objMemory.state.needEnergy = true
        // 更新当前挂载的需求资源任务。ps：20240125好像会导致carrier的逻辑出现问题
        // if (!objMemory['state']['needEnergy']) {
        //     objMemory.publishTask.map(taskID => {
        //         let taskDeta = taskManager.getTaskByID(taskID, this.id, this.pos.roomName, false)
        //         if (taskDeta.taskType == taskType.needResource) {
        //             if (taskDeta.doing) return  //已经被领取的任务则跳过
        //             taskManager.finishTask(taskID, this.pos.roomName)
        //         }
        //     })
        // }
    },
    /**获取任务 */
    getTask: function () {

    },
    /**推送任务 */
    pushTask: function () {

    },
    test: function () { }
}


export default _mountExtension